package com.softserveinc.fragments;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.Menu;
import android.support.v4.view.MenuItem;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.softserveinc.MovieManagerApplication;
import com.softserveinc.R;
import com.softserveinc.data.MovieDataManager.MovieDetailsCallBack;
import com.softserveinc.fragments.utils.Image;
import com.softserveinc.model.Movie;
import com.softserveinc.model.MovieDetails;
import com.softserveinc.model.MovieDetailsData;

public class MovieDetailsFragment extends Fragment implements
		MovieDetailsCallBack {

	private static final String SHARE_TEXT = "I've enjoyed!!!";

	public static final String MOVIE_PARAM_NAME = "Movie";

	public static final String TAG = MovieDetailsFragment.class.getSimpleName();

	private static final String DATE_FORMAT = "dd-MM-yyyy";

	private static final CharSequence N_A = "n/a";

	private final Map<Integer, FrameLayout> imagesLayoutMap = new HashMap<Integer, FrameLayout>();

	private final List<Image> thumbs = new ArrayList<Image>();

	private MovieManagerApplication application;

	private OnImageClickListener imageClickListener;

	private Movie movie;
	private MovieDetails movieDetails;

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		Log.i(TAG, "Created");

		movie = getArguments().getParcelable(MOVIE_PARAM_NAME);

		application = (MovieManagerApplication) getActivity()
				.getApplicationContext();

		setHasOptionsMenu(true);
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();

		application.getDataManager().interruptLoadingMovieDetails(this);
		application.getDataManager().interruptLoadingThumbsOnDetails(this);
	}

	@Override
	public void onConfigurationChanged(final Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		if (movieDetails != null) {
			LinearLayout layout = (LinearLayout) getView().findViewById(
					R.id.layout_image_container);
			layout.removeAllViews();

			showProgressOnImages(movieDetails.getThumbHttpUrls().size());

			setPreviousLoadedImages();
		}
	}

	@Override
	public void onActivityCreated(final Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		imageClickListener = (OnImageClickListener) getActivity();
	}

	@Override
	public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
		inflater.inflate(R.menu.details_menu, menu);
	}

	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_share:
			share(movie.getTitle(), SHARE_TEXT + " " + movie.getTitle());
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public View onCreateView(final LayoutInflater inflater,
			final ViewGroup container, final Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		application.getDataManager().manageDataForMovieDetails(movie, this);
		View view = inflater.inflate(R.layout.movie_details, container, false);

		TextView titleText = (TextView) view
				.findViewById(R.id.value_movie_title);
		titleText.setText(movie.getTitle());

		ImageView poster = (ImageView) view.findViewById(R.id.icon_big_poster);

		if (movie.getPoster() == null || movie.getPoster().isRecycled()) {
			view.findViewById(R.id.icon_big_poster_progress_bar).setVisibility(
					View.VISIBLE);
			application.getDataManager().loadPosterOnDetailsScreen(movie, this);
		} else {
			poster.setImageBitmap(movie.getPoster());
		}

		TextView releaseDateText = (TextView) view
				.findViewById(R.id.value_release_date);

		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
		Date releaseDate = movie.getReleaseDate();
		if (releaseDate == null || releaseDate.getYear() == 1900) {
			releaseDateText.setText(N_A);
		} else {
			releaseDateText.setText(format.format(releaseDate));
		}

		Button playTrailerButton = (Button) view
				.findViewById(R.id.button_play_trailer);
		playTrailerButton.setVisibility(View.INVISIBLE);

		return view;
	}

	@Override
	public void loadPoster(final Movie movie) {
		getView().findViewById(R.id.icon_big_poster_progress_bar)
				.setVisibility(View.GONE);

		ImageView poster = (ImageView) getView().findViewById(
				R.id.icon_big_poster);

		poster.setImageBitmap(movie.getPoster());
	}

	@Override
	public void postExecute(final MovieDetailsData data) {

		View view = getView();
		if (view != null) {
			final MovieDetails movieDetails = data.getMovieDetails();

			Log.d(TAG, "details: " + movieDetails);

			TextView overviewText = (TextView) view
					.findViewById(R.id.value_movie_overview);
			overviewText.setText(movieDetails.getOverview());

			TextView castText = (TextView) view.findViewById(R.id.value_cast);
			castText.setText(movieDetails.getCast());

			Button playTrailerButton = (Button) view
					.findViewById(R.id.button_play_trailer);
			playTrailerButton.setVisibility(View.VISIBLE);
			playTrailerButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(final View v) {
					setupPlayTrailerAction(movieDetails.getTrailerUrl());
				}
			});

			Log.i(TAG, "thumb urls size:"
					+ movieDetails.getThumbHttpUrls().size());
			for (String string : movieDetails.getThumbHttpUrls()) {
				Log.i(TAG, "url " + string);
			}

			this.movieDetails = movieDetails;
			showProgressOnImages(movieDetails.getThumbHttpUrls().size());

			thumbs.clear();
			application.getDataManager().manageDataForMovieDetailsImages(
					movieDetails, this);
		}
	}

	private void showProgressOnImages(final int size) {
		View view = getView();

		if (view != null) {
			imagesLayoutMap.clear();

			LinearLayout images = (LinearLayout) view
					.findViewById(R.id.layout_image_container);

			for (int i = 0; i < size; i++) {

				View imageRow = View.inflate(view.getContext(),
						R.layout.image_row, null);

				LinearLayout imageRowLayout = (LinearLayout) imageRow
						.findViewById(R.id.layout_image_row);

				for (int j = 0; j < imageRowLayout.getChildCount(); j++, i++) {
					FrameLayout layout = (FrameLayout) imageRowLayout
							.getChildAt(j);

					if (i >= size) {
						while (j < imageRowLayout.getChildCount()) {
							layout = (FrameLayout) imageRowLayout.getChildAt(j);

							layout.findViewById(R.id.progress_bar_on_thumb)
									.setVisibility(View.GONE);
							layout.setBackgroundColor(Color.WHITE);
							j++;
						}
						break;
					}

					ImageView imageView = (ImageView) layout
							.findViewById(R.id.icon_thumb);
					imageView.setVisibility(View.INVISIBLE);

					imagesLayoutMap.put(i, layout);
				}

				images.addView(imageRow);
			}
		}
	}

	protected void setupPlayTrailerAction(final String url) {
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse(url), "video/*");
		startActivity(i);
	}

	public void share(final String subject, final String text) {
		final Intent intent = new Intent(Intent.ACTION_SEND);

		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_SUBJECT, subject);
		intent.putExtra(Intent.EXTRA_TEXT, text);

		startActivity(Intent.createChooser(intent, getString(R.string.share)));
	}

	@Override
	public void loadImage(final Image image, final int index) {
		setImage(image, index);

		thumbs.add(image);
	}

	private void setImage(final Image image, final int index) {
		if (imagesLayoutMap.containsKey(index)) {
			FrameLayout frameLayout = imagesLayoutMap.get(index);

			ImageView imageView = (ImageView) frameLayout
					.findViewById(R.id.icon_thumb);

			imageView.setImageBitmap(image.getBitmap());

			imageView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(final View v) {
					imageClickListener.onImageClick(image.getPosterUrl());
				}
			});

			imageView.setVisibility(View.VISIBLE);

			frameLayout.findViewById(R.id.progress_bar_on_thumb).setVisibility(
					View.GONE);

			frameLayout.setBackgroundColor(Color.WHITE);
		}
	}

	private void setPreviousLoadedImages() {
		for (int index = 0; index < thumbs.size(); index++) {
			setImage(thumbs.get(index), index);
		}
	}

	public interface OnImageClickListener {

		void onImageClick(final String imageName);
	}

	public void setImageClickListener(
			final OnImageClickListener imageClickListener) {
		this.imageClickListener = imageClickListener;
	}
}
